//lire firxtXML.xml et generer XMLAltarica.xml
package expressToAltaRica;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ExpressToAltarica {
	
	//la methode createComponentFamily nous cree pour chaque famille de composants l'element componentFamily
	//qui contienne les componentModel
	public static Element createComponentFamily(String nameComponent, Document document_read, Document document_write){
		Element componentFamily = document_write.createElement("COMPONENT_FAMILY");
		Element identification_family = document_write.createElement("IDENTIFICATION");
		identification_family.setAttribute("name",nameComponent);
		componentFamily.appendChild(identification_family);
		NodeList components = document_read.getElementsByTagName(nameComponent);
		int nb_components = components.getLength();
		//on parcourt tous les composants de nom nameComponent, et pour chaque composant on cree un composantModel
		for(int i=0;i<nb_components;i++){
			Element componentModel = document_write.createElement("COMPONENT_MODEL");
			Element identification_model = document_write.createElement("IDENTIFICATION");
			identification_model.setAttribute("name",nameComponent);
			componentModel.appendChild(identification_model);
			NodeList fils = (components.item(i)).getChildNodes();
			int nb_fils = fils.getLength();
			//pour chaque componentModel on remplit son identification et des interfaces
			for(int k=0 ; k<nb_fils ; k++){
				Node aux = fils.item(k); 
				//mnt si le fils possede un attribut(comme ca on elimine les espaces blanc(de type Text)), et la valeur de son 
				//attribut type est MFHA_out ou MFHA_in alors on ajoute une interface IO dans le componentModel
				if((aux.hasAttributes())&&(((((Element)aux).getAttribute("type"))).equals("MFHA_in_interface")||((((Element)aux).getAttribute("type"))).equals("MFHA_out_interface"))){
					Element io = document_write.createElement("IO");
					io.setAttribute("name", aux.getNodeName());
					io.setAttribute("direction",((Element)aux).getAttribute("type"));
					componentModel.appendChild(io);
				}
			}
			
			componentFamily.appendChild(componentModel);
			
		}
		
		return componentFamily;
	}
	
	public static List<Element> createInstances(String nameComponent, Document document_read, Document document_write){
		NodeList components = document_read.getElementsByTagName(nameComponent);
		int nb_components = components.getLength();
		List<Element> instances = new ArrayList<Element>();
		
		for(int i=0;i<nb_components;i++){
			Element component = document_write.createElement("Component");
			component.setAttribute("name", ((((Element)(components.item(i))).getElementsByTagName("name")).item(0)).getTextContent());
			component.setAttribute("Family",nameComponent);
			System.out.println("aaaa: " + ((((Element)(components.item(i))).getElementsByTagName("name")).item(0)).getTextContent());
			instances.add(component);
		}
		
		
		return instances;
	}
	
	public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException{
		
		//On lit notre XML
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document_read = builder.parse("firstXML.xml");
		
		//Et on contruit un nouveau XML
		DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
		DocumentBuilder constructeur = fabrique.newDocumentBuilder();
		Document document_write = constructeur.newDocument();
		
		document_write.setXmlVersion("1.0");
		document_write.setXmlStandalone(true);
		
		//Et on commence � le remplir
		//on ecrit d abord les componentFamily 
		Element racine = document_write.createElement("Export");
		Element componentFamily_activator = createComponentFamily("activator",document_read,document_write);
		Element componentFamily_ob = createComponentFamily("ob",document_read,document_write);
		Element componentFamily_op = createComponentFamily("op",document_read,document_write);
		document_write.appendChild(racine);
		racine.appendChild(componentFamily_activator);
		racine.appendChild(componentFamily_ob);
		racine.appendChild(componentFamily_op);
		
		//apres on remplit les instances dans Project
		Element project = document_write.createElement("Project");
		List<Element> instances_activator = createInstances("activator", document_read, document_write);
		Iterator iterator = instances_activator.iterator();
		while(iterator.hasNext()){
			Element component = (Element)iterator.next();
			project.appendChild(component);
		}
		List<Element> instances_op = createInstances("op", document_read, document_write);
		iterator = instances_op.iterator();
		while(iterator.hasNext()){
			Element component = (Element)iterator.next();
			project.appendChild(component);
		}
		racine.appendChild(project);
		try
	    {
	       DOMSource domSource = new DOMSource(document_write);
	       StringWriter writer = new StringWriter();
	       StreamResult result = new StreamResult(writer);
	       TransformerFactory tf = TransformerFactory.newInstance();
	       Transformer transformer = tf.newTransformer();
	       transformer.transform(domSource, result);
	       String text = writer.toString();
	       System.out.println("text: " + text);
	       
			FileWriter fw = new FileWriter ("XMLAltarica.xml");
			BufferedWriter bw = new BufferedWriter (fw);
			PrintWriter fichierSortie = new PrintWriter (bw); 
			fichierSortie.println (text); 
			fichierSortie.close();
			
	    }
		
		 catch(TransformerException ex)
		 {
		       ex.printStackTrace();
		 }
		catch (Exception e)
		{
			System.out.println(e.toString());
		}
		
	}
}
